package per.com.service.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import per.com.bean.Order;
import per.com.bean.User;
import per.com.common.Const;
import per.com.common.ServerResponse;
import per.com.common.TokenCache;
import per.com.dao.PcUsersDao;
import per.com.service.PcUsersService;
import per.com.utils.MD5Utils;
import per.com.utils.UUidUtils;


/**
 * @author zxy
 */
@Service("PcUsersServiceId")
public class PcUsersServiceImpl implements PcUsersService {
    @Autowired
    @Qualifier("PcUsersDaoId")
    private PcUsersDao pcUsersDao;

    @Override
    public ServerResponse<User> login(String username, String password) {
        int resultCount = pcUsersDao.checkUsername(username);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("用户名已经存在");
        }
        String md5Password = MD5Utils.encodedByMD5(password);
        User users = pcUsersDao.login(username , md5Password);
        if (users == null){
            return ServerResponse.createByErrorMessage("密码错误");
        }
        return ServerResponse.createBySuccess("登录成功" , users);
    }

    @Override
    public ServerResponse register(User user) {

        int resultCount = pcUsersDao.checkUsername(user.getUsername());
        if (resultCount > 0){
            return ServerResponse.createByErrorMessage("用户名已经存在，请更换用户名");
        }
        user.setStatus(Const.Role.ROLE_CUSTOMER);
        user.setUid(UUidUtils.getId());
        user.setIsfreeze(Const.freeze.freeze_no);
        user.setCreditScore(Const.CREDIT_SCORE);
        String md5Password = MD5Utils.encodedByMD5(user.getPassword());
        user.setPassword(md5Password);
        resultCount = pcUsersDao.insert(user);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }

        return ServerResponse.createBySuccessMessage("注册成功");
    }

    @Override
    public ServerResponse checkValid(String str, String type) {

        if (StringUtils.isNotBlank(type)){
            if (Const.USERNAME.equals(type)){
                int resultCount = pcUsersDao.checkUsername(str);
                if (resultCount > 0){
                    return ServerResponse.createByErrorMessage("用户名已经存在");
                }
            }
        }else {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    @Override
    public ServerResponse getQuestion(String username) {

        ServerResponse response = this.checkValid(username , Const.USERNAME);
        if (response.isSuccess()){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        String question = pcUsersDao.getQuestion(username);
        if (StringUtils.isNotBlank(question)){
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("找回密保得密保问题是空得");
    }

    @Override
    public ServerResponse checkAnswer(String username, String question, String answer) {

        int resultCount = pcUsersDao.checkAnswer(username , question , answer);
        if (resultCount > 0){
            String forgetToken = UUidUtils.getId();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX + username , forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题得答案错误");
    }

    @Override
    public ServerResponse forgetRestPassword(String username, String passwordNew, String forgetToken) {

        if (StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMessage("参数错误，token需要传递");
        }
        ServerResponse response = this.checkValid(username , Const.USERNAME);
        if (response.isSuccess()){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
        if (StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token无效或者过期");
        }
        if (StringUtils.equals(forgetToken , token)){
            String md5Password = MD5Utils.encodedByMD5(passwordNew);
            int resultCount = pcUsersDao.restPassword(md5Password , username);
            if (resultCount > 0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        }else {
            return ServerResponse.createByErrorMessage("token无效，请重置获取密码得token");
        }

        return ServerResponse.createByErrorMessage("修改密码失败");
    }

    @Override
    public ServerResponse restPassword(String passwordOld, String passwordNew , User user) {

        String md5Password = MD5Utils.encodedByMD5(passwordOld);
        int resultCount = pcUsersDao.checkPassword(user.getUid() , md5Password);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Utils.encodedByMD5(passwordNew));
        int updateResult = pcUsersDao.updateByPrimaryKeySelective(user);
        if (updateResult > 0){
            return ServerResponse.createBySuccessMessage("密码修改成功");
        }

        return ServerResponse.createByErrorMessage("密码修改失败");
    }

    @Override
    public ServerResponse<User> updateInformation(User user) {

        User updateUser = new User();
        updateUser.setUid(user.getUid());
        updateUser.setUsername(user.getUsername());
        updateUser.setAnswer(user.getAnswer());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setSex(user.getSex());
        updateUser.setTel(user.getTel());

        int resultCount = pcUsersDao.updateByPrimaryKeySelective(updateUser);
        if (resultCount > 0){
            return ServerResponse.createBySuccess("个人信息修改成功" , updateUser);
        }

        return ServerResponse.createByErrorMessage("个人信息修改失败");
    }

    @Override
    public User getUserById(String userId) {
        return pcUsersDao.getUserById(userId);
    }


}
